"ui";
activity.window.addFlags(android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
activity.window.setStatusBarColor(android.graphics.Color.TRANSPARENT);
activity.window.getDecorView().setSystemUiVisibility(android.view.View.SYSTEM_UI_FLAG_LAYOUT_STABLE | android.view.View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

ui.layout(
    <vertical>
        <linear id="appbar" orientation="vertical" h="90" bg="#f14567">
            <View h="40" w="*"/>
            <linear orientation="horizontal" h="50">
                <View w="50" h="50"/>
                <text id="app_name" textSize="18sp" textStyle="bold" textColor="#ffffff" w="0" layout_weight="1"  text="大白神器集中营" h="50" gravity="center"/>
                <img id="exit" src="@drawable/ic_power_settings_new_black_48dp" algin="right" padding="12" tint="#ffffff" w="50" h="50" foreground="?selectableItemBackground" />
            </linear>
        </linear>

        <frame h="*" bg="#ffffff">
            <vertical>

                <text textSize="18" textStyle="bold" textColor="black" text="可运行插件" w="*" gravity="center_vertical" margin="15 25 15 15"/>

                <linear orientation="horizontal" h="64"margin="10 0 10 0">
                    <vertical id="video" w="0" h="*" layout_weight="1" bg="?attr/selectableItemBackground" clickable="true" layout_gravity="center">
                        <img src="https://gitee.com/wupk/auto.test/raw/master/img/%E8%A7%86%E9%A2%91.png" w="*" h="40" gravity="center"/>
                        <text text="视频" color="#000000"  gravity="center" size="14" w="*"/>
                    </vertical>
                    <vertical id="news" w="0" h="*" layout_weight="1" bg="?attr/selectableItemBackground" clickable="true" layout_gravity="center">
                        <img src="https://gitee.com/wupk/auto.test/raw/master/img/%E6%96%B0%E9%97%BB.png" w="*" h="40" gravity="center"/>
                        <text text="新闻" color="#000000" gravity="center" size="14" w="*"/>
                    </vertical>

                    <vertical id="book" w="0" h="*" layout_weight="1" bg="?attr/selectableItemBackground" clickable="true" layout_gravity="center">
                        <img src="https://gitee.com/wupk/auto.test/raw/master/img/%E5%B0%8F%E8%AF%B4.png" w="*" h="40" gravity="center"/>
                        <text text="小说" color="#000000"  gravity="center" size="14" w="*"/>
                    </vertical>

                    <vertical id="wine" w="0" h="*" layout_weight="1"  bg="?attr/selectableItemBackground" clickable="true" layout_gravity="center">
                        <img src="https://gitee.com/wupk/auto.test/raw/master/img/%E8%B4%AD%E7%89%A9.png" w="*" h="40" gravity="center"/>
                        <text text="抢购" color="#000000"  gravity="center" size="14" w="*"/>
                    </vertical>
                </linear>

                <text textSize="18" textStyle="bold" textColor="black" text="其他设置" w="*" gravity="center_vertical" margin="15"/>
                
                <horizontal h="46" margin="15 0 15 0">
                    <img src="@drawable/ic_accessible_black_48dp" tint="#616161" h="46" w="46" padding="10"/>
                    <Switch id="autoService" w="*" h="*" text="无障碍服务" textColor="#000000" gravity="center_vertical" checked="{{auto.service != null}}" textSize="14sp"/>
                </horizontal>
                <View w="*" h="1" bg="#f4f5f6" margin="15 0 15 0"/>
                <horizontal id="app_log" h="46" margin="15 0 15 0">
                    <img src="@drawable/ic_assignment_black_48dp" tint="#616161" h="46" w="46" padding="10"/>
                    <text textSize="14" h="*" textColor="#000000" text="日志管理" w="*" gravity="center_vertical"/>
                </horizontal>
                <View w="*" h="1" bg="#f4f5f6" margin="15 0 15 0"/>
                <horizontal id="app_setting" h="46" margin="15 0 15 0">
                    <img src="@drawable/ic_settings_black_48dp" tint="#616161" h="46" w="46" padding="10"/>
                    <text textSize="14" h="*" textColor="#000000" text="系统设置" w="*" gravity="center_vertical"/>
                </horizontal>
                <View w="*" h="1" bg="#f4f5f6" margin="15 0 15 0"/>
                <horizontal id="app_about" h="46" margin="15 0 15 0">
                    <img src="@drawable/ic_info_outline_black_48dp" tint="#616161" h="46" w="46" padding="10"/>
                    <text textSize="14" h="*" textColor="#000000" text="关于我们" w="*" gravity="center_vertical"/>
                </horizontal>
                <View w="*" h="1" bg="#f4f5f6" margin="15 0 15 0"/>


                
            </vertical>
        </frame>
    </vertical>
);

//设置导航栏背景色
ui.appbar.backgroundDrawable = GradientDrawable("LEFT_RIGHT", ["#FFFF9700", "#FFED1C24"])
/**
 * 程序退出事件
 */
ui.exit.click(() => {
    confirm("确定要退出程序吗?").then(value=>{
        if(value){
			ui.finish();
        }
    });
});

ui.wine.click(() =>{
    loadDatas("https://gitee.com/wupk/auto.test/raw/master/test/wine/main.js");
    // threads.start(function(){
    //     var Url = "https://gitee.com/wupk/auto.test/raw/master/test/wine/main.js";
    //     var res_script = http.get(Url, {
    //         headers: {
    //             'Accept-Language': 'en-us,en;q=0.5',
    //             'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11'
    //         }
    //     });
    //     var video = res_script.body.string();
    //     if (res_script.statusCode == 200){
    //         engines.execScript("wine", video);
    //     }
    // });
});


ui.book.click(() =>{
    loadDatas("https://gitee.com/wupk/auto.test/raw/master/test/book/main.js");
    // threads.start(function(){
    //     var Url = "https://gitee.com/wupk/auto.test/raw/master/test/book/main.js";
    //     var res_script = http.get(Url, {
    //         headers: {
    //             'Accept-Language': 'en-us,en;q=0.5',
    //             'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11'
    //         }
    //     });
    //     var video = res_script.body.string();
    //     engines.execScript("book", video);
    // });
});

/**
 * 加载脚本
 * @param {脚本地址}} url 
 */
function loadDatas(url){
    threads.start(function(){
        var res_script = http.get(url, {
            headers: {
                'Accept-Language': 'en-us,en;q=0.5',
                'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11'
            }
        });
        var test = res_script.body.string();
        if (res_script.statusCode == 200){
            engines.execScript("test", test);
        }else{
            loadDatas(url);
        }
    });
}

/**
 * 监听返回按键
 */
ui.emitter.on("back_pressed", e => {
    confirm("确定要退出程序吗?").then(value=>{
        if(value){
            ui.finish();
        }
    });
    e.consumed = true;
});

/**
 * 开启无障碍服务
 */
function enableAbs() {
    importClass(android.content.Context);
    importClass(android.provider.Settings);
    var packageName = context.getPackageName();
    var absPermittedByshell = false;
    try {
        var enabledServices = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
        log('当前已启用的辅助服务\n', enabledServices);
        if (enabledServices.indexOf(packageName) >= 0 && auto.service != null) {
            log("已经开启无障碍服务，无需重复开启");
        } else {
            var Services = enabledServices + ":" + packageName + "/com.stardust.autojs.core.accessibility.AccessibilityService";
            Settings.Secure.putString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, Services);
            Settings.Secure.putString(context.getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED, '1');
            log("成功开启无障碍服务");
        }
        return true
    } catch (error) {
        if (absPermittedByshell == false && shell("pm grant " + packageName + " android.permission.WRITE_SECURE_SETTINGS", true).code == 0) {
            log("已成功使用shell开启无障碍服务授权");
            absPermittedByshell = true;
            return this.enableAbs()
        } else {
            if (absPermittedByshell == true) {
                log("shell开启授权成功，但仍然无法顺利开启无障碍服务，请手动开启！");
                return false;
            } else {
                log("使用shell开启授权失败");
                return false
            }
        }
        log("使用Shell开启无障碍失败，错误:" + error);
    }
}

ui.autoService.on("check", function(checked) {
    if (checked && auto.service == null) {
        var absPermittedByshell = false;
        try {
            var en = enableAbs();
        } catch (e) {
            log(e);
            var en = false;
        }
        if (en != true) {
            app.startActivity({
                action: "android.settings.ACCESSIBILITY_SETTINGS"
            });
        }
    }
    if (!checked && auto.service != null) {
        let view = ui.inflate(
            <vertical padding="25 0" bg="#ffffff">
                        <linear orientation="horizontal" align="left" margin="0" paddingTop="10">
                            <img src="@drawable/ic_warning_black_48dp" h="20" marginTop="3" tint="#F44336" layout_gravity="center"/>
                            <text text="您确定要关闭“无障碍服务”吗？" textSize="15" textStyle="bold" margin="0 5 10 0" textColor="#F44336"/>
                        </linear>
                        <text text="本软件内的所有脚本均需要“无障碍服务”，若您关闭“无障碍服务”，本软件内的所有脚本都将立即无法工作，请确认" textStyle="bold" textSize="12" margin="10 10 10 5" textColor="#D32F2F"/>
                        <linear orientation="horizontal" align="left" margin="0" paddingTop="10" paddingBottom="10">
                            <card layout_weight="50" h="40" cardCornerRadius="5dp" cardElevation="0dp" gravity="center_vertical" margin="5"cardBackgroundColor="#F44336">
                                <text id="Determine" text="确认关闭" textStyle="bold" textColor="#FFFFFF" gravity="center" textSize="12sp" foreground="?attr/selectableItemBackground" clickable="true"/>
                            </card>
                            <card layout_weight="50" h="40" cardCornerRadius="5dp" cardElevation="0dp" gravity="center_vertical" margin="5"cardBackgroundColor="#4CAF50">
                                <text id="cancel" text="保持开启" textStyle="bold" textColor="#FFFFFF" gravity="center" textSize="12sp" foreground="?attr/selectableItemBackground" clickable="true"/>
                            </card>
                        </linear>
                    </vertical>, null, false);
        view.cancel.click(() => {
            ui.autoService.setChecked(true);
            DHK.dismiss();
        });
        view.Determine.click(() => {
            auto.service.disableSelf();
            DHK.dismiss();
        });
        var DHK = dialogs.build({
            customView: view,
            wrapInScrollView: false,
            autoDismiss: false,
            cancelable: false
        }).show();
    }
});

ui.video.click(() => {
    threads.start(function(){
        var Url = "https://gitee.com/wupk/auto.test/raw/master/test/video/video_select.js";
        var res_script = http.get(Url, {
            headers: {
                'Accept-Language': 'en-us,en;q=0.5',
                'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11'
            }
        });
        var video = res_script.body.string();
        engines.execScript("test", video);
    });
});

ui.app_log.click(() => {
    app.startActivity({
        action: "android.intent.action.VIEW",
        packageName: "com.w.auojs.turbo",
        className: "com.w.auojs.turbo.LogActivity"
    });
});

ui.app_setting.click(() => {
    app.startActivity("settings");
});

ui.app_about.click(() => {
    app.startActivity("about");
});

function Color(color) {
    return android.graphics.Color.parseColor(color);
}

function GradientDrawable(orientation, color) {
    var colors = [];
    color.forEach(color => colors.push(Color(color)));
    return new android.graphics.drawable.GradientDrawable(android.graphics.drawable.GradientDrawable.Orientation[orientation], colors);
}